let movableAreaWidth = 0
let movableViewWidth = 0
const backgroundAudioManager = wx.getBackgroundAudioManager()
let currentSec = -1 // 当前的秒数
let duration = 0 // 当前歌曲的总时长, 以秒为单位
let isMoving = false // 表示当前进度条是否在拖拽，解决：当进度条拖动时候和updatetime事件有冲突的问题
Component({
  properties: {
    isSame: Boolean,
    isVIP: Boolean
  },
  data: {
    showTime: {
      currentTime: '00:00',
      totalTime: '00:00'
    },
    movableDis: '',
    progress: ''
  },
  lifetimes: {
    ready() {
      // 重新进入同一首歌，总时间显示 00:00, 需要重新设置
      if (this.properties.isSame && this.data.showTime.totalTime === '00:00') {
        this.setTime()
      }
      this.getMovableDis()
      this.bindBGMEvent()
    }
  },
  methods: {
    onChange(e) {
      // 拖动
      if (e.detail.source === 'touch') {
        this.data.progress = e.detail.x / (movableAreaWidth - movableViewWidth) * 100
        this.data.movableDis = e.detail.x
        isMoving = true
        // console.log('change', isMoving)
      }
    },
    onTouchEnd() {
      const currentTimeFmt = this.dateFormat(Math.floor(backgroundAudioManager.duration))
      this.setData({
        ['showTime.currentTime']: `${currentTimeFmt.min}:${currentTimeFmt.sec}`,
        progress: this.data.progress,
        movableDis: this.data.movableDis
      })
      // 音乐播放的进度
      backgroundAudioManager.seek(duration * this.data.progress / 100)
      isMoving = false
      // console.log('end', isMoving)
    },
    getMovableDis() {
      const query = this.createSelectorQuery()
      query.select('.movable-area').boundingClientRect()
      query.select('.movable-view').boundingClientRect()
      query.exec(rect => {
        movableAreaWidth = rect[0].width
        movableViewWidth = rect[1].width
      })
    },
    bindBGMEvent() {
      backgroundAudioManager.onPlay(() => {
        console.log('onPlay')
        // 有点时候执行onTouchEnd事件后，还会触发onChange事件
        isMoving = false
        this.triggerEvent('musicPlay')
      })

      backgroundAudioManager.onStop(() => {
        // console.log('onStop')
      })

      backgroundAudioManager.onPause(() => {
        console.log('onPause')
        this.triggerEvent('musicPause')
      })

      backgroundAudioManager.onWaiting(() => {
        // console.log('onWaiting')
      })

      backgroundAudioManager.onCanplay(() => {
        // console.log('onCanplay')
        // 有的机型 backgroundAudioManager.duration 获取的是 undefined
        if (typeof backgroundAudioManager.duration != 'undefined') {
          this.setTime()
        } else {
          setTimeout(() => {
            this.setTime()
          }, 1000)
        }
      })

      backgroundAudioManager.onTimeUpdate(() => {
        if (!isMoving) {
          // console.log('onTimeUpdate')
          const currentTime = backgroundAudioManager.currentTime
          const duration = backgroundAudioManager.duration
          // 优化
          const sec = currentTime.toString().split('.')[0]
          if (sec != currentSec) {
            // console.log(currentTime)
            const currentTimeFmt = this.dateFormat(currentTime)
            this.setData({
              ['showTime.currentTime']: `${currentTimeFmt.min}:${currentTimeFmt.sec}`,
              movableDis: (movableAreaWidth - movableViewWidth) * currentTime / duration,
              progress: currentTime / duration * 100
            })
            currentSec = sec
            
            // 联动歌词
            this.triggerEvent('timeUpdate', {
              currentTime
            })
          }
        }
      })

      backgroundAudioManager.onEnded(() => {
        // console.log('onEnded')
        this.triggerEvent('musicEnd')
      })

      backgroundAudioManager.onError(res => {
        console.error(res.errMsg)
        console.error(res.errCode)
        wx.showToast({
          title: '错误' + res.errCode,
        })
      })
    },
    setTime() {
      duration = backgroundAudioManager.duration
      const durationFmt = this.dateFormat(duration)
      this.setData({
        ['showTime.totalTime']: `${durationFmt.min}:${durationFmt.sec}`
      })
    },
    // 格式化时间
    dateFormat(sec) {
      const min = Math.floor(sec / 60)
      sec = Math.floor(sec % 60)
      return {
        'min': this.parse0(min),
        'sec': this.parse0(sec)
      }
    },
    parse0(sec) {
      return sec < 10 ? '0' + sec : sec
    }
  }
})